import * as THREE from 'three'
import createApp from '../../core'

const createRaycaster = (dom: HTMLElement) => {
  const { camera, scene } = createApp(dom)
  scene.background = new THREE.Color(0xdddddd)
  camera.position.set(-150, 100, 120)
  camera.lookAt(scene.position)

  scene.add(new THREE.AmbientLight(0xffffff, 0.3))

  const light = new THREE.DirectionalLight(0xffffff, 0.35)
  light.position.set(1, 1, 1).normalize()
  scene.add(light)

  const geometry = new THREE.BoxGeometry(20, 20, 20)
  for (let i = 0; i < 1500; i++) {
    const object = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ color: Math.random() * 0xffffff }))

    object.position.x = Math.random() * 800 - 400
    object.position.y = Math.random() * 800 - 400
    object.position.z = Math.random() * 800 - 400

    scene.add(object)
  }

  const raycaster = new THREE.Raycaster()
  const mouse = new THREE.Vector2()
  dom.addEventListener('mouseup', (event: MouseEvent) => {
    const { clientX, clientY } = event
    mouse.x = ((clientX - dom.offsetLeft) / dom.offsetWidth * 2) - 1
    mouse.y = -((clientY - dom.offsetTop) / dom.offsetHeight * 2) + 1
    raycaster.setFromCamera(mouse, camera)
    const intersects = raycaster.intersectObjects(scene.children, false)
    const mesh = intersects[0] && intersects[0].object as THREE.Mesh
    if (mesh && mesh.material) {
      const material = mesh.material as THREE.MeshLambertMaterial
      material.emissive.setHex(0xff0000)
    }
  })
}

export {
  createRaycaster
}
